const state = {
  user: {
    token: '',
    username: '',
    photo: '',
  }
}

const getters = {
  isLogin: state => {
    if (state.user.token == '') {
      state.user.token = localStorage.getItem('token')
    }
    return state.user.token != ''
  },
  token: state => {
    if (state.user.token == '') {
      state.user.token = localStorage.getItem('token')
    }
    return state.user.token
  },
  username: state => {
    if (state.user.username == '') {
      state.user.username = localStorage.getItem('username')
    }
    return state.user.username
  },
  photo: state => {
    if (state.user.photo == '') {
      state.user.photo = localStorage.getItem('photo')
    }
    return state.user.photo
  },

}

const mutations = {
  login (state, {user}) {
    state.user.token = user.token
    localStorage.setItem('token', user.token)

  },
  logout (state) {
    state.user.token = ''
    localStorage.setItem('token', '')
    state.user.username = ''
    localStorage.setItem('username', '')
    state.user.photo = ''
    localStorage.setItem('photo', '')
  },
  updateUserInfo (state, {user}) {
    state.user.username = user.username
    state.user.photo = user.photo

    localStorage.setItem('username', user.username)
    localStorage.setItem('photo', user.photo)
  }
}

const actions = {
  login ({state, commit}, user) {
    commit('login', {user})
  },
  logout ({commit},) {
    commit('logout')
  },
  updateUserInfo ({state, commit}, user) {
    commit('updateUserInfo', {user})
  },
}

export default {
  state,
  getters,
  mutations,
  actions
}
